# @Version        : 1.0
# @Update Time    : 2025/3/15 15:34
# @File           : carousel.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
import flet as ft
import time
from threading import Thread
from typing import Literal


class Carousel(ft.Container):
    def __init__(
        self,
        images: list[str],
        interval: int = 3,
        height: int = 400,
        index: int = 0,
        border_radius: int = 5,
        directions: Literal[1, 2, 3, 4, 5, 6] = 1,
        axis: Literal["horizontal", "vertical"] = "vertical",
        **kwargs
    ):
        """
        轮播图组件，继承自 ft.Container

        :param images: 图片列表
        :param interval: 每张图片显示时间（秒）
        :param height: 轮播图高度
        :param index: 开始轮播图索引
        :param border_radius: 圆角设置
        :param axis: 轮播图小按钮方向vertical：垂直，horizontal：水平
        :param kwargs: 其他 Container 的参数
        """
        super().__init__(**kwargs)
        self.images = images
        self.interval = interval
        self.current_index = index
        self.border_radius = border_radius
        self.height = height

        # 创建圆点按钮
        self.dot_buttons = [
            ft.IconButton(
                ft.icons.FIBER_MANUAL_RECORD,
                icon_size=15,
                style=ft.ButtonStyle(
                    bgcolor=ft.colors.TRANSPARENT,
                    overlay_color=ft.colors.TRANSPARENT,
                ),
                on_click=lambda e, idx=i: self.change_image(idx),
            )
            for i in range(len(self.images))
        ]

        # 圆点按钮行
        self.dots_row = self.set_alignment(directions, axis)
        # 初始化 Container 的内容
        self.content = ft.Row(
            [
                ft.Container(
                    image_src=self.images[0],
                    image_fit=ft.ImageFit.COVER,
                    width=300,  # 默认宽度
                    height=height,  # 默认高度
                    expand=1,
                    border_radius=ft.border_radius.all(border_radius),
                    content=self.dots_row
                )
            ]
        )

        # 自动轮播线程
        self.carousel_thread = Thread(target=self.start_carousel, daemon=True)

    def change_image(self, index):
        """切换图片"""
        self.current_index = index

        self.content = ft.Row(
            [
                ft.Container(
                    image_src=self.images[index],
                    image_fit=ft.ImageFit.COVER,
                    width=300,  # 默认宽度
                    height=self.height,  # 默认高度
                    expand=1,
                    border_radius=ft.border_radius.all(self.border_radius),
                    content=self.dots_row
                )
            ]
        )

        # 更新圆点按钮状态
        for i, dot in enumerate(self.dot_buttons):
            dot.icon_color = ft.colors.GREY if i != index else ft.colors.GREEN
        self.update()

    def start_carousel(self):
        """自动轮播图片"""
        while True:
            time.sleep(self.interval)  # 轮播间隔时间
            self.current_index = (self.current_index + 1) % len(self.images)
            self.change_image(self.current_index)

    # 设置圆点按钮对齐方式

    def set_alignment(self, directions: int = 1, axis: Literal["horizontal", "vertical"] = "vertical"):
        # 定义对齐方式的映射
        alignment_mapping = {
            1: (ft.MainAxisAlignment.START, ft.CrossAxisAlignment.START),
            2: (ft.MainAxisAlignment.CENTER, ft.CrossAxisAlignment.START),
            3: (ft.MainAxisAlignment.END, ft.CrossAxisAlignment.START),
            4: (ft.MainAxisAlignment.START, ft.CrossAxisAlignment.END),
            5: (ft.MainAxisAlignment.CENTER, ft.CrossAxisAlignment.END),
            6: (ft.MainAxisAlignment.END, ft.CrossAxisAlignment.END),
        }
        # 获取对齐方式
        alignment, vertical_alignment = alignment_mapping.get(
            directions,
            (ft.MainAxisAlignment.START, ft.CrossAxisAlignment.START)
        )

        # 根据方向创建 Row 或 Column
        if axis == "horizontal":
            dots_row = ft.Row(
                controls=self.dot_buttons,
                alignment=alignment,
                vertical_alignment=vertical_alignment,
                spacing=10,
            )
        else:
            dots_row = ft.Column(
                controls=self.dot_buttons,
                alignment=alignment,
                horizontal_alignment=vertical_alignment,
                spacing=10,
            )

        return dots_row

    def start(self):
        """启动自动轮播"""
        if not self.carousel_thread.is_alive():
            self.carousel_thread.start()

    # 停止自动轮播
    def stop(self):
        """停止自动轮播"""
        if self.carousel_thread.is_alive():
            self.carousel_thread.join()
